#!/usr/bin/env python3
import os
import sys
import re

"""
这个将目录下的整个md转为常规的数学符号 $ $$
"""
def replace_in_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # 替换 [ ] 为 $$
    content = re.sub(r'\\\[|\\\]', '$$', content)

    # 替换 ( ) 为 $
    content = re.sub(r'\\\(|\\\)|\\\( |\s\\\)', '$', content)

    # 替换公式的空格
    content = re.sub(r'$ ', '$', content)
    content = re.sub(r' $', '$', content)

    # 处理多行冒号格式问题
    # 匹配  claude 后面跟着任意数量的空行和空格，然后是一个冒号的情况
    content = re.sub(r'[\s\n]*：', ':', content)
    content = re.sub(r'[\s\n]*:', ':', content)

    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(content)

def process_directory(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.md'):
                file_path = os.path.join(root, file)
                print(f"Processing: {file_path}")
                replace_in_file(file_path)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python script.py <directory_path>")
        sys.exit(1)

    directory = sys.argv[1]
    if not os.path.isdir(directory):
        print(f"Error: {directory} is not a valid directory")
        sys.exit(1)

    process_directory(directory)
    print("Processing complete.")


# python3 md_replacer.py /path/to/your/markdown/files
